#!/bin/bash

# 停止所有服务

echo "=========================================="
echo "停止所有GeoGebra服务"
echo "=========================================="

# 检查是否在项目根目录
if [ ! -f "fastapi_app.py" ] || [ ! -d "services" ]; then
    echo "错误: 请从项目根目录执行此脚本"
    echo "正确用法: ./deploy/stop_all_services.sh"
    echo "当前目录: $(pwd)"
    exit 1
fi

# 查找并停止相关进程
echo "查找相关进程..."

# 停止占用8080端口的进程
PORT_8080_PID=$(lsof -ti :8080 2>/dev/null)
if [ ! -z "$PORT_8080_PID" ]; then
    echo "停止端口8080上的进程 (PID: $PORT_8080_PID)..."
    kill -TERM $PORT_8080_PID 2>/dev/null
    sleep 2
    if kill -0 $PORT_8080_PID 2>/dev/null; then
        echo "强制停止端口8080上的进程..."
        kill -KILL $PORT_8080_PID 2>/dev/null
    fi
    echo "✓ 端口8080已清理"
else
    echo "端口8080未被占用"
fi

# 停止占用8001端口的进程
PORT_8001_PID=$(lsof -ti :8001 2>/dev/null)
if [ ! -z "$PORT_8001_PID" ]; then
    echo "停止端口8001上的进程 (PID: $PORT_8001_PID)..."
    kill -TERM $PORT_8001_PID 2>/dev/null
    sleep 2
    if kill -0 $PORT_8001_PID 2>/dev/null; then
        echo "强制停止端口8001上的进程..."
        kill -KILL $PORT_8001_PID 2>/dev/null
    fi
    echo "✓ 端口8001已清理"
else
    echo "端口8001未被占用"
fi

# 停止占用8002端口的进程
PORT_8002_PID=$(lsof -ti :8002 2>/dev/null)
if [ ! -z "$PORT_8002_PID" ]; then
    echo "停止端口8002上的进程 (PID: $PORT_8002_PID)..."
    kill -TERM $PORT_8002_PID 2>/dev/null
    sleep 2
    if kill -0 $PORT_8002_PID 2>/dev/null; then
        echo "强制停止端口8002上的进程..."
        kill -KILL $PORT_8002_PID 2>/dev/null
    fi
    echo "✓ 端口8002已清理"
else
    echo "端口8002未被占用"
fi

# 停止所有uvicorn进程（如果有的话）
echo "检查是否有其他uvicorn进程..."
UVICORN_PIDS=$(pgrep -f uvicorn 2>/dev/null)
if [ ! -z "$UVICORN_PIDS" ]; then
    echo "发现其他uvicorn进程: $UVICORN_PIDS"
    echo "停止这些进程..."
    for pid in $UVICORN_PIDS; do
        kill -TERM $pid 2>/dev/null
    done
    sleep 2
    # 检查是否还有残留进程
    REMAINING_PIDS=$(pgrep -f uvicorn 2>/dev/null)
    if [ ! -z "$REMAINING_PIDS" ]; then
        echo "强制停止残留进程: $REMAINING_PIDS"
        for pid in $REMAINING_PIDS; do
            kill -KILL $pid 2>/dev/null
        done
    fi
    echo "✓ 所有uvicorn进程已清理"
else
    echo "未发现其他uvicorn进程"
fi

echo "=========================================="
echo "所有服务已停止"
echo "=========================================="

# 验证端口是否已清理
echo "验证端口状态："
lsof -i :8080 2>/dev/null | grep LISTEN && echo "警告: 端口8080仍被占用" || echo "✓ 端口8080已清理"
lsof -i :8001 2>/dev/null | grep LISTEN && echo "警告: 端口8001仍被占用" || echo "✓ 端口8001已清理"
lsof -i :8002 2>/dev/null | grep LISTEN && echo "警告: 端口8002仍被占用" || echo "✓ 端口8002已清理" 